package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.model.entity.Course;
import com.example.model.dto.CourseRequest;
import com.example.mapper.CourseMapper;
import com.example.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Override
    public List<Course> listCourses() {
        return courseMapper.findAll();
    }
    
    @Override
    public Course getCourseById(Integer id) {
        Course course = courseMapper.findById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        return course;
    }
    
    @Override
    public Course addCourse(CourseRequest courseRequest) {
        // 检查课程名是否已存在
        Course existCourse = courseMapper.findByCourseName(courseRequest.getCourseName());
        if (existCourse != null) {
            throw new RuntimeException("课程名称已存在");
        }
        
        Course course = new Course();
        course.setCourseName(courseRequest.getCourseName());
        save(course);
        return course;
    }
    
    @Override
    public Course updateCourse(CourseRequest courseRequest) {
        // 检查课程是否存在
        Course course = getCourseById(courseRequest.getId());
        
        // 检查新课程名是否与其他课程重复
        Course existCourse = courseMapper.findByCourseName(courseRequest.getCourseName());
        if (existCourse != null && !existCourse.getId().equals(courseRequest.getId())) {
            throw new RuntimeException("课程名称已存在");
        }
        
        course.setCourseName(courseRequest.getCourseName());
        courseMapper.update(course);
        
        return course;
    }
    
    @Override
    public void deleteCourse(Integer id) {
        // 检查课程是否存在
        getCourseById(id);
        courseMapper.deleteById(id);
    }

    @Override
    public List<Course> list() {
        return courseMapper.findAll();
    }
} 